from Sms import Sms
import redis
import config
import time





def main():
    sms_obj = Sms()
    sms_obj.login()
    while True:
        redis_obj = redis.StrictRedis(
            host=config.redisServer,
            port=1111,
            db=13,
            decode_responses=True,
            password="Fmsuh1J50R%T*Lq15TL#IkWb#oMp^@0OYzx5Q2CSEEs$v9dd*mnqRFByoeGZ"
        )

        redis_key = "XHS::XIANSUO::LIST::PHONENUM::SIGNAL"
        signal = redis_obj.rpop(redis_key)

        redis_key = "XHS::XIANSUO::LIST::PHONENUM"
        redis_key_set = "XHS::XIANSUO::SET::PHONENUM"   # 存储使用过的手机号
        while True:
            if signal and redis_obj.llen(redis_key) < 5:
                phonenum = sms_obj.get_phonenum()
                if not redis_obj.sismember(redis_key_set, phonenum):
                    print("获取新手机号 -->", phonenum)
                    redis_obj.lpush(redis_key, phonenum)
                    redis_obj.sadd(redis_key_set, phonenum)
                else:
                    print("手机号已经使用过")
            else:
                break

        redis_key = "XHS::XIANSUO::HASH::PHONENUM"
        phonenum_keys = redis_obj.hkeys(redis_key)
        if phonenum_keys:
            # result = sms_obj.get_code(",".join(phonenum_keys))
            # print("result -->", result)
            for phonenum in phonenum_keys:
                result = sms_obj.get_code(phonenum)

                redis_key = "XHS::XIANSUO::HASH::PHONENUM"
                t = redis_obj.hget(redis_key, phonenum)
                print("result -->", result, t)
                if "验证码" in result or (time.time() - int(t.split('.')[0])) > 200:
                    redis_obj.hdel(redis_key, phonenum)
                redis_key = "XHS::XIANSUO::KEY::PHONENUM::{phonenum}".format(phonenum=phonenum)
                redis_obj.set(redis_key, result)



if __name__ == '__main__':
    while 1:
        try:
            main()
        except:
            pass
